package gui;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
 
public class SearchTextField extends SearchIconTF implements FocusListener {
	
	private static final long serialVersionUID = 1L;
	
	private String textWhenNotFocused;
 
    public SearchTextField() {
        super();
        this.textWhenNotFocused = "Tìm kiếm...";
        this.addFocusListener(this);
        this.setFont(getFont().deriveFont(14f));
        this.setForeground(Color.GRAY);
        
        BufferedImage img = null;
		try {
		    img = ImageIO.read(new File("Images/find.png"));
		    setIcon(new ImageIcon(img));
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
 
    public String getTextWhenNotFocused() {
        return this.textWhenNotFocused;
    }
 
    public void setTextWhenNotFocused(String newText) {
        this.textWhenNotFocused = newText;
    }
 
    @Override
    protected void paintComponent(Graphics g) {
    	super.paintComponent(g);
 
        if (!this.hasFocus() && this.getText().equals("")) {
            int height = this.getHeight();
            Font prev = g.getFont();
            Font italic = prev.deriveFont(Font.ITALIC);
            g.setFont(italic);
            g.setColor(Color.GRAY);
            int h = g.getFontMetrics().getHeight();
            int textBottom = (height - h) / 2 + h - 2;
            int x = this.getInsets().left;
            Graphics2D g2d = (Graphics2D) g;
            RenderingHints hints = g2d.getRenderingHints();
            g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            g2d.drawString(textWhenNotFocused, x, textBottom);
            g2d.setRenderingHints(hints);
        }
    }
 
    public void focusGained(FocusEvent e) {
        this.repaint();
    }
 
    public void focusLost(FocusEvent e) {
        this.repaint();
    }
}